import { defineConfig } from 'unocss';
import { presetUno } from 'unocss';
import presetRemToPx from '@unocss/preset-rem-to-px';

const rules = [
	/* ========== 布局增强 ========== */
	// 显示方式统一处理
	[
		/^display-(none|block|inline|inline-block|flex|inline-flex|gridz|flex-root|inline-grid|table|table-row|table-cell|list-item)$/,
		([, value]) => ({ display: value })
	],

	// 定位优化
	[/^position-(relative|absolute|fixed|sticky|static)$/, ([, value]) => ({ position: value })],

	// 浮动增强
	[/^float-(left|right|none|inherit|initial)$/, ([, value]) => ({ float: value })],

	/* ========== 边框优化扩展 ========== */
	// 圆角优化
	[
		/^b-radius-(\d+)(r?em|px|vw|vh|%)?$/,
		([, size, unit = 'px']) => ({
			'border-radius': `${size}${unit}`
		})
	],

	// 基础边框（支持样式/颜色）
	[
		/^b(?:-(t|b|l|r|x|y|))?-(\d+)(?:-([a-z]+))?(?:-(\S+))?$/,
		([, dir, width, style = 'solid', color]) => {
			const directions = {
					t: 'top',
					b: 'bottom',
					l: 'left',
					r: 'right',
					x: ['left', 'right'],
					y: ['top', 'bottom']
				}[dir],
				value = color ? `${width}px ${style} ${color}` : `${width}px ${style}`;

			if (directions) {
				return Array.isArray(directions) ? Object.fromEntries(directions.map((d) => [`border-${d}`, value])) : { [`border-${directions}`]: value };
			} else {
				return { border: value };
			}
		}
	],

	/* ========== 内边距优化 ========== */
	// 外边距/内边距统一处理（支持更多单位）
	[
		/^([mp])(?:-(t|b|l|r|x|y|))?-(-?\d+)(r?em|px|vw|vh|%)?$/,
		([, type, dir, value, unit = 'px']) => {
			const prop = type === 'm' ? 'margin' : 'padding';

			const directions = {
				t: 'top',
				b: 'bottom',
				l: 'left',
				r: 'right',
				x: ['left', 'right'],
				y: ['top', 'bottom']
			}[dir] || ['top', 'right', 'bottom', 'left'];

			const styles = Array.isArray(directions)
				? Object.fromEntries(directions.map((d) => [`${prop}-${d}`, `${value}${unit}`]))
				: { [`${prop}-${directions}`]: `${value}${unit}` };

			type === 'p' && (styles['box-sizing'] = 'border-box');

			return styles;
		}
	],

	/* ========== 尺寸扩展 ========== */
	// 支持多种单位 (px/rem/vw/vh/%)
	[
		/^(min-|max-)?(w|h)-(\d+)(px|r?em|vw|vh|%)?$/,
		([, prefix, type, size, unit = 'px']) => ({
			[`${prefix || ''}${type === 'w' ? 'width' : 'height'}`]: `${size}${unit}`
		})
	],

	/* ========== 文字增强 ========== */
	// 字体大小支持单位格式
	[
		/^f-s-(\d+)(px|r?em)?$/,
		([, size, unit = 'px']) => ({
			'font-size': `${size}${unit}`
		})
	],

	// 支持多种颜色格式
	[
		/^text-(#[\da-fA-F]{3,6}|rgb\(\d+,\s*\d+,\s*\d+\)|var\(--.+\))$/,
		([, color]) => ({
			color
		})
	],

	// 文字对齐
	[
		/^text-(left|right|center|justify|start|end|inherit|initial)$/,
		([, type]) => ({
			'text-align': type
		})
	],

	// 字体粗细
	[
		/^font-(thin|light|normal|medium|bold|black)$/,
		([, weight]) => ({
			'font-weight': {
				thin: 100,
				light: 300,
				normal: 400,
				medium: 500,
				bold: 700,
				black: 900
			}[weight]
		})
	],

	/* ========== 背景增强 ========== */
	// 修复拼写错误并支持渐变
	[
		/^bg-(#[\da-fA-F]{3,6}|rgb\(\d+,\s*\d+,\s*\d+\)|linear-gradient\(.+\)|var\(--.+\))$/,
		([, bg]) => ({
			background: bg
		})
	],

	/* ========== 阴影增强 ========== */
	[
		/^shadow-(\d+)(?:-(#[\da-fA-F]{3,6}|rgb\(\d+,\s*\d+,\s*\d+\)|var\(--.+\)))?$/,
		([, level, color = 'rgba(0,0,0,0.1)']) => ({
			'box-shadow': `0 ${level * 2}px ${level * 4}px ${color}`
		})
	],

	/* ========== 其他优化 ========== */
	// Z-index 增强
	[
		/^z-(auto|\d+|max)$/,
		([, value]) => ({
			'z-index': value === 'max' ? 2147483647 : value
		})
	],

	// 光标扩展
	[
		/^cursor-(alias|copy|move|zoom-in|zoom-out|not-allowed|pointer|text|wait|grab|grabbing)$/,
		([, type]) => ({
			cursor: type
		})
	],

	// 鼠标事件
	[
		(/^pointer-events-(none|auto|visiblePainted|visibleFill|visibleStroke|painted|fill|stroke|all|inherit)$/,
		([, type]) => ({
			'pointer-events': type
		}))
	],

	// 滚动条
	[
		/^overflow(?:-(x|y))?-(visible|hidden|scroll|auto)$/,
		([, dir, type]) => ({
			[`${dir ? `overflow-${dir}` : 'overflow'}`]: type
		})
	]
];

const flexRules = [
	/* ========== 核心 Flex 规则 ========== */
	// 基础 flex 容器
	['flex', { display: 'flex' }],

	// flex 方向
	// directions
	['flex-row', { display: 'flex', 'flex-direction': 'row' }],
	['flex-row-reverse', { display: 'flex', 'flex-direction': 'row-reverse' }],
	['flex-col', { display: 'flex', 'flex-direction': 'column' }],
	['flex-col-reverse', { display: 'flex', 'flex-direction': 'column-reverse' }],

	/* ========== 主轴/侧轴对齐 ========== */
	// 主轴对齐
	[
		/^justify-(start|end|center|between|around|evenly|stretch)$/,
		([, type]) => ({
			'justify-content':
				{
					start: 'flex-start',
					end: 'flex-end',
					between: 'space-between',
					around: 'space-around',
					evenly: 'space-evenly',
					stretch: 'stretch'
				}[type] || type
		})
	],

	[
		/^align-(start|end|center|between|around|evenly|stretch)$/,
		([, type]) => ({
			'align-content':
				{
					start: 'flex-start',
					end: 'flex-end',
					between: 'space-between',
					around: 'space-around',
					evenly: 'space-evenly',
					stretch: 'stretch'
				}[type] || type
		})
	],

	// 侧轴对齐
	[
		/^items-(start|end|center|baseline|stretch|flex-start|flex-end)$/,
		([, type]) => ({
			'align-items': type
		})
	],

	/* ========== Flex 项属性 ========== */
	// flex-grow/shrink/basis
	[
		/^(?:flex-)?(grow|shrink|basis)(?:-(\d+))?$/,
		([, type, value = '1']) => ({
			[`flex-${type}`]: value
		})
	],

	// flex 简写
	[/^flex-(\d+)$/, ([, value]) => ({ flex: value })],
	['flex-auto', { flex: '1 1 auto', 'min-width': 0, 'min-height': 0 }],
	['flex-initial', { flex: '0 1 auto' }],
	['flex-none', { flex: 'none' }]
];

const flexShortcuts = [
	/* ========== 常用组合 ========== */
	{ 'flex-center': 'flex items-center justify-center' },
	{ 'flex-col-center': 'flex-col items-center justify-center' },
	{ 'flex-between': 'flex justify-between items-center' },
	{ 'flex-stretch': 'flex items-stretch justify-stretch' },
	{ pointer: 'cursor-pointer' }
];

export default defineConfig({
	presets: [
		presetUno(),
		// unocss 默认 rem，转成 px
		presetRemToPx({
			baseFontSize: 4, // 1rem = 4px
			enablePxComment: false // 禁用注释提高性能
		})
	],
	rules: [...rules, ...flexRules],
	shortcuts: [...flexShortcuts],
	content: {
		pipeline: {
			// 明确指定需要扫描的文件类型
			include: [/\.vue$/, /\.vue\?vue/, /\.tsx?$/, /\.jsx?$/],
			// 排除不需要扫描的目录
			exclude: ['node_modules', 'dist']
		}
	}
});
